package org.wiming.learn;

import com.google.common.collect.Lists;
import lombok.experimental.UtilityClass;
import org.wiming.TreeNode;

import java.util.*;

/**
 * @author : wenchao.long
 * @date : Created in 2021/01/28 14:47 周四
 * @description : 二叉树
 */
@UtilityClass
@SuppressWarnings("unused")
public class TreeNodeLearn {

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = Lists.newArrayList();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>() {{
            push(root);
        }};
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            res.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = Lists.newArrayList();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = Lists.newLinkedList();
        if (root == null) {
            return res;
        }
        Deque<TreeNode> deque = new LinkedList<TreeNode>() {{
            push(root);
        }};
        while (!deque.isEmpty()) {
            TreeNode node = deque.pop();
            res.push(node.val);
            if (node.left != null) {
                deque.push(node.left);
            }
            if (node.right != null) {
                deque.push(node.right);
            }
        }
        return res;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = Lists.newArrayList();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>() {{
            add(root);
        }};
        while (!queue.isEmpty()) {
            List<Integer> ans = Lists.newArrayList();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                ans.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            res.add(ans);
        }
        return res;
    }
}
